package com.example.hello.controller;

import com.example.hello.common.PageResult;
import com.example.hello.common.Result;
import com.example.hello.entity.Order;
import com.example.hello.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDate;

@RestController
public class OrderController {

    private static final Logger log = LoggerFactory.getLogger(OrderController.class);

    @Autowired
    private OrderService orderService;

    /**
     * 1. 分页查询订单列表
     */
    @GetMapping("/orders")
    public Result<PageResult<Order>> getOrderList(
            @RequestParam(required = false) String number,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) Integer empId,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startTime,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endTime,
            @RequestParam(required = false, defaultValue = "1") Integer page,
            @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        
        try {
            log.info("查询订单列表: number={}, status={}, empId={}, startTime={}, endTime={}, page={}, pageSize={}",
                     number, status, empId, startTime, endTime, page, pageSize);
            
            PageResult<Order> pageResult = orderService.getOrderList(
                    number, status, empId, startTime, endTime, page, pageSize);
            return Result.success(pageResult);
        } catch (Exception e) {
            log.error("查询订单列表失败", e);
            return Result.error("查询订单列表失败：" + e.getMessage());
        }
    }

    /**
     * 2. 新增订单
     */
    @PostMapping("/orders")
    public Result<Integer> addOrder(@RequestBody Order order) {
        try {
            log.info("新增订单: {}", order);
            Integer id = orderService.addOrder(order);
            return Result.success(id);
        } catch (IllegalArgumentException e) {
            log.error("新增订单参数错误", e);
            return Result.error(e.getMessage());
        } catch (Exception e) {
            log.error("新增订单失败", e);
            return Result.error("新增订单失败：" + e.getMessage());
        }
    }

    /**
     * 3. 修改订单
     */
    @PutMapping("/orders/{id}")
    public Result<Void> updateOrder(@PathVariable Integer id, @RequestBody Order order) {
        try {
            log.info("修改订单: id={}, order={}", id, order);
            boolean success = orderService.updateOrder(id, order);
            if (success) {
                return Result.success();
            } else {
                return Result.error("修改订单失败，订单不存在");
            }
        } catch (IllegalArgumentException e) {
            log.error("修改订单参数错误", e);
            return Result.error(e.getMessage());
        } catch (Exception e) {
            log.error("修改订单失败", e);
            return Result.error("修改订单失败：" + e.getMessage());
        }
    }

    /**
     * 4. 删除订单
     */
    @DeleteMapping("/orders/{id}")
    public Result<Void> deleteOrder(@PathVariable Integer id) {
        try {
            boolean success = orderService.deleteOrder(id);
            if (success) {
                return Result.success();
            } else {
                return Result.error("删除订单失败");
            }
        } catch (IllegalStateException e) {
            // 捕获并返回业务异常信息
            return Result.error(e.getMessage());
        } catch (Exception e) {
            log.error("删除订单异常", e);
            return Result.error("删除订单失败：" + e.getMessage());
        }
    }

    /**
     * 5. 查询订单详情
     */
    @GetMapping("/orders/{id}")
    public Result<Order> getOrderById(@PathVariable Integer id) {
        try {
            log.info("查询订单详情: id={}", id);
            Order order = orderService.getOrderById(id);
            if (order != null) {
                return Result.success(order);
            } else {
                return Result.error("订单不存在");
            }
        } catch (Exception e) {
            log.error("查询订单详情失败", e);
            return Result.error("查询订单详情失败：" + e.getMessage());
        }
    }

    /**
     * 6.1 取消订单
     */
    @PutMapping("/orders/{id}/cancel")
    public Result<Void> cancelOrder(@PathVariable Integer id) {
        try {
            log.info("取消订单: id={}", id);
            boolean success = orderService.cancelOrder(id);
            if (success) {
                return Result.success();
            } else {
                return Result.error("取消订单失败，订单不存在");
            }
        } catch (IllegalStateException e) {
            log.error("取消订单失败", e);
            return Result.error(e.getMessage());
        } catch (Exception e) {
            log.error("取消订单失败", e);
            return Result.error("取消订单失败：" + e.getMessage());
        }
    }

    /**
     * 6.2 完成订单
     */
    @PutMapping("/orders/{id}/complete")
    public Result<Void> completeOrder(@PathVariable Integer id) {
        try {
            log.info("完成订单: id={}", id);
            boolean success = orderService.completeOrder(id);
            if (success) {
                return Result.success();
            } else {
                return Result.error("完成订单失败，订单不存在");
            }
        } catch (IllegalStateException e) {
            log.error("完成订单失败", e);
            return Result.error(e.getMessage());
        } catch (Exception e) {
            log.error("完成订单失败", e);
            return Result.error("完成订单失败：" + e.getMessage());
        }
    }
} 